/*
 * WinLoop.cpp
 *
 *  Created on: 2012-12-18
 *      Author: yangentao@gmail.com
 */
#include "WinLoop.h"
#include "LastError.h"
#include "StreamLog.h"

namespace yet {

WinLoop::WinLoop() {
	threadID = 0;
	looping = false;
}

WinLoop::~WinLoop() {
	if(isLooping()){
		slog<<err<<"not quit when object destructing"<<endln;
		quit(0);
	}
}

int WinLoop::loop() {
	threadID = GetCurrentThreadId();
	BOOL ret = 0;
	MSG msg = { 0 };
	looping =  true;
	while (ret = GetMessage(&msg, 0, 0, 0)) {
		if (ret == -1) {
			LastError e;
			e.print();
			break;
		} else {
			if(OnPreTranslateMsg){
				if(OnPreTranslateMsg(&msg)){
					continue;
				}
			}
			if(OnTranslateAccelator){
				if(OnTranslateAccelator(&msg)){
					continue;
				}
			}
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}
	looping = false;
	return ret == -1 ? -1 : msg.wParam;
}
void WinLoop::quit(int exitCode){
	if(threadID && looping){
		postMessage(WM_QUIT, exitCode, 0);
	}
}
bool WinLoop::isLooping(){
	return looping;
}
bool WinLoop::postMessage(UINT msg, DWORD wParam, DWORD lParam){
	if(!threadID){
		return false;
	}
	return 0 != PostThreadMessage(threadID, msg, wParam, lParam);
}

} /* namespace yet */
